#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>

#include <sys/shm.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>

#define SHM_NAME "./sha_file"
#define SHM_SIZE 4096
int shmid;
void *addr;

void my_exit(int sig)
{
    if(sig == SIGINT)
    {
        shmdt(addr);
        shmctl(shmid, IPC_RMID, NULL);
        exit(1);
    }

}

int main()
{
    __pid_t pid;

    key_t key;

    key = ftok(SHM_NAME, 's');

    shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT);

    if (shmid < 0)
    {
        perror("shmget error!");
        exit(1);
    }

    printf("key = %x\n", key);
    printf("shmid = %d\n", shmid);

    signal(SIGINT,my_exit);

    pid = fork();

    if (pid < 0)
    {
        perror("fork error!");
        exit(1);
    }
    else if (pid == 0)
    {
        char buffer[1024];
        addr = shmat(shmid, NULL, 0);
        if (addr == (void *)-1)
        {
            perror("shm at error!");
            exit(1);
        }

        while (1)
        {
            memset(buffer, 0, sizeof(buffer));
            
            scanf("%s", buffer);
            memcpy(addr, buffer, strlen(buffer));
            kill(getppid(),SIGUSR1);
        }
    }
    else
    {
        char buffer[1024];
        signal(SIGUSR1,my_exit);
        addr = shmat(shmid, NULL, 0);
        if (addr == (void *)-1)
        {
            perror("shm at error!");
            exit(1);
        }

        while (1)
        {
            memset(buffer, 0, sizeof(buffer));
            // memset(buffer, 0, sizeof(buffer));
            // memcpy(buffer, addr, strlen((char *)addr));
            // printf("recv data = %s\n",buffer);
            // memset(addr,0,SHM_SIZE);

            pause();
            
            memcpy(buffer, addr, strlen((char *)addr));
            printf("recv data = %s\n",buffer);
            memset(addr,0,SHM_SIZE);

            sleep(1);
        }
    }

    

    return 0;
}
